<template>
  <view class="page">
    <u-navbar :fixed="false" leftIcon=" " :autoBack="false" title="购物车" placeholder bgColor="#fff" />
    <u-swipe-action autoClose v-if="shopCarList.length">
      <view class="gwc-list">
      <u-swipe-action-item @click="swipeAction($event, item)" :options="actionOptions" :disabled="item.status!='1'" :index="1" :threshold="100" v-for="(item, index) in shopCarList" :key="index">
        <view class="inventory-box" :class="{'take-down': item.status!='1'}">
          <view class="gwc-item">
            <image class="goods-img" :src="item.subtitle?item.subtitle.split(',')[0]:''" mode="aspectFill" />
            <view class="u-flex-1">
              <view class="name u-line-2">{{ item.title }}</view>
              <view class="spec" v-if="item.status=='1'"><text class="u-line-1">{{ item.skuName }}</text><u-icon name="arrow-down" color="#818181" size="24rpx"></u-icon></view>
              <view class="take-down-tips" v-else>商品已下架</view>
              <view class="u-flex u-row-between u-col-bottom">
                <template v-if="item.status=='1'">
                  <view class="price"><text>¥</text> {{ (item.priceCents/100).toFixed(2) }}</view>
                  <u-number-box
                    integer
                    disabledInput
                    :min="1"
                    :max="item.stock"
                    v-model="item.quantity"
                    asyncChange
                    @change="numChange($event, index)"
                    button-size="52rpx"
                  ></u-number-box>
                </template>
                <template v-else>
                  <view style="color: #FF6600;font-size: 24rpx;line-height: 44rpx;">下拉刷新后将自动移除</view>
                  <view class="remove" @click="delGoods([item.id])">立即移除</view>
                </template>
              </view>
            </view>
          </view>
          <view class="u-flex u-row-between u-m-t-20" v-if="(item.stock <= 10 || item.stock < item.quantity) && item.status=='1'">
            <view class="inventory-tips" v-if="item.stock < item.quantity">该商品剩余库存不足！</view>
            <view class="inventory-tips" v-else>该商品剩余库存不多了，尽快下单购买！</view>
            <view class="inventory-num">仅剩{{ item.stock }}件</view>
          </view>
        </view>
      </u-swipe-action-item>
      </view>
    </u-swipe-action>
    <view class="gwc-empty" v-else>
      <image src="../../static/gwcEmpty.png" />
      <view>您尚未添加商品到购物车</view>
    </view>
    <view class="u-text-center u-m-b-24" v-if="hotProductsList.length">
      <image style="width: 149.62rpx;height: 40rpx;" src="../../static/hot.png" />
    </view>
    <view class="goods-list">
      <view class="goods-item" v-for="item in hotProductsList" :key="item.id" @click="jumpTo('/pages/goodsDetail/goodsDetail?id='+item.id)">
        <image style="width: 344rpx;height: 344rpx;flex-shrink: 0;" :src="item.subtitle?item.subtitle.split(',')[0]:''" mode="aspectFill" />
        <view class="name u-line-2">{{ item.title }}</view>
        <view class="u-flex u-row-between u-p-l-12 u-p-r-12 u-p-b-22">
          <view class="price"><text>¥</text> {{ (item.price / 100).toFixed(2) }}</view>
          <view class="num">仅剩{{ item.stock }}件</view>
        </view>
      </view>
    </view>
    <view class="settlement" v-if="shopCarInfo.goodsNum">
      <view class="settlement-text">共{{ shopCarInfo.goodsNum }}件商品，合计：<text>¥ {{ shopCarInfo.totalAmount}}</text></view>
      <view class="gwc-btn" @click="confirmOrder">立即购买</view>
    </view>
    <specPopup v-if="showSpecPopup" :closePopup="() => showSpecPopup=false" :showSpecPopup="showSpecPopup" />
    <customTabbar value="3" />
  </view>
</template>

<script>
import customTabbar from '../../components/customTabbar.vue'
import specPopup from '../../components/specPopup.vue'
import { getCartsList, gethotProductsList, editShopCar, delShopCar, collectGoods } from '@/api/index'

export default {
  components: {
    customTabbar,
    specPopup,
  },
  data() {
    return {
      hotProductsList: [],
      shopCarList: [],
      shopCarInfo: {},
      value: 1,
      showSpecPopup: false,
      loading: false,
      actionOptions: [{
        text: '收藏',
        style: {
          backgroundColor: '#56CB03'
        }
      },
      {
        text: '删除',
        style: {
          backgroundColor: '#E30000'
        }
      }],
      pendingRequests: new Map(),
    };
  },
  onLoad() {
    this.gethotProducts()
  },
  onShow() {
    this.getShopCar()
  },
  methods: {
    swipeAction(e, item) {
      if(e.index == 0) {
        // 收藏
        collectGoods({ userId: uni.getStorageSync('userInfo').userId, productId: item.productId }).then(res => {
        })
        this.delGoods([item.id])
      } else if(e.index == 1) {
        // 删除
        this.delGoods([item.id])
      } 
    },
    // 删除商品
    async delGoods(id) {
      await delShopCar({id}).then(res => {
        this.getShopCar()
        this.calculate()
      })
    },
    // 购物车商品
    getShopCar() {
      uni.showLoading({ mask: true })
      getCartsList({}).then(res => {
        uni.hideLoading()
        this.shopCarList = res.rows
        this.calculate()
        uni.stopPullDownRefresh();
      })
    },
    calculate() {
      const filterGoodsList = this.shopCarList.filter(v => v.status == '1' && v.stock >= v.quantity)
      this.shopCarInfo = {
        filterGoodsList,
        goodsNum: filterGoodsList.length,
        freightAmount: (filterGoodsList.reduce((total, item) => {
          return total + ((item.freightAmount/100) * item.quantity);
        }, 0)).toFixed(2),
        totalAmount: (filterGoodsList.reduce((total, item) => {
          return total + ((item.priceCents/100) * item.quantity);
        }, 0)).toFixed(2),
      }
    },
    // 热销榜单
    async gethotProducts() {
      uni.showLoading({ mask: true })
      await gethotProductsList({quantity: 20, categoryType: 0, deptId: uni.getStorageSync('userInfo').deptId || 100}).then(res => {
        uni.hideLoading()
        this.hotProductsList = res.data
      })
    },
    numChange(e, index) {
      const that = this
      const item = {...this.shopCarList[index]}
      this.$nextTick(() => {
        item.quantity = e.value
        this.$set(this.shopCarList, index, item)
        that.calculate()
      })
      
      const itemId = item.id || index
      
      // 取消之前同一商品的未完成请求
      if (this.pendingRequests.has(itemId)) {
        clearTimeout(this.pendingRequests.get(itemId))
      }
      
      // 设置新的延迟请求
      const timer = setTimeout(() => {
        this.loading = true
        editShopCar(item).then(res => {
          this.loading = false
          this.pendingRequests.delete(itemId)
        }).catch(error => {
          this.loading = false
          this.pendingRequests.delete(itemId)
          console.error('修改购物车失败:', error)
        })
      }, 800) // 800ms 后调用
      
      this.pendingRequests.set(itemId, timer)
    },
    confirmOrder() {
      if(uni.getStorageSync('userInfo').postId == 103) {
        uni.showToast({
          icon: 'none',
          title: '请先开通vip'
        })
        return
      }
      if(this.loading) {
        return
      }
      uni.setStorageSync('shopCarInfo', this.shopCarInfo)
      this.jumpTo('/pages/confirmOrder/confirmOrder')
    }
  },

  async onPullDownRefresh() {
    uni.showLoading()
    const ids = this.shopCarList.filter(v => v.status != '1').map(v => v.id).join(',')
    if(ids) {
      await delGoods(ids)
    }
    this.getShopCar()
  },
};
</script>

<style lang="scss" scoped>
.page {
	width: 750rpx;
	min-height: 100vh;
  background: #F5F5F5;
  position: relative;
  .gwc-list {
    width: 702rpx;
    margin: 0 auto;
    margin-bottom: 26rpx;
    margin-top: 12rpx;
    display: flex;
    flex-direction: column;
    gap: 12rpx;
    .inventory-box {
      width: 100%;
      background: #FFFFFF;
      border-radius: 12rpx;
      padding: 20rpx 16rpx;
      .inventory-tips {
        width: 462rpx;
        height: 48rpx;
        line-height: 48rpx;
        text-align: center;
        background: #F7F7F7;
        border-radius: 200rpx;
        font-size: 24rpx;
      }
      .inventory-num {
        font-size: 24rpx;
        color: #E20300;
      }
    }
    .gwc-item {
      display: flex;
      gap: 20rpx;
      position: relative;
      .goods-img {
        width: 180rpx;height: 180rpx;flex-shrink: 0;
      }
      .name {
        height: 88rpx;
        font-size: 28rpx;
        color: #000000;
        line-height: 44rpx;
        margin-bottom: 2rpx;
      }
      .spec {
        width: 182rpx;
        height: 44rpx;
        background: #F7F7F7;
        border-radius: 8rpx;
        border: 2rpx solid #E1E1E1;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 12rpx;
        text {
          width: 112rpx;
          font-size: 24rpx;
          color: #818181;
        }
      }
      .price {
        font-weight: 500;
        font-size: 28rpx;
        color: #E20300;
        text {
          font-size: 24rpx;
        }
      }
    }
    .take-down {
      background-color: #E1E1E1;
    }
    .take-down .goods-img::before {
      content: '';
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background: rgba(0,0,0,0.2);
    }
    .take-down .goods-img::after {
      content: '已下架';
      width: 108rpx;
      height: 34rpx;
      background: rgba(0,0,0,0.5);
      border-radius: 200rpx;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%,-50%);
      display: flex;
      align-items: center;
      justify-content: center;
      color: #fff;
      font-size: 24rpx;
    }
    .take-down .name {
      color: #818181;
    }
    .take-down .take-down-tips {
      font-size: 24rpx;
      line-height: 44rpx;
    }
    .take-down .remove {
      width: 144rpx;
      height: 48rpx;
      line-height: 48rpx;
      text-align: center;
      background: #FFFFFF;
      border-radius: 200rpx;
      border: 2rpx solid #FF6600;
      font-size: 24rpx;
      color: #FF6600;
    }
  }
  .gwc-empty {
    width: 702rpx;
    height: 320rpx;
    background: #FFFFFF;
    border-radius: 12rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    gap: 48rpx;
    font-size: 24rpx;
    margin: 12rpx auto 38rpx;
    image {
      width: 172rpx;
      height: 126.72rpx;
    }
  }
  .goods-list {
    width: 702rpx;
    display: flex;
    flex-wrap: wrap;
    gap: 12rpx 14rpx;
    margin: 0 auto;
    .goods-item {
      width: 344rpx;
      background: #fff;
      border-radius: 8rpx;
      .name {
        margin-top: 16rpx;
        margin-bottom: 14rpx;
        padding: 0 12rpx;
        font-size: 28rpx;
        color: #000000;
        line-height: 44rpx;
      }
      .price {
        font-weight: 500;
        font-size: 28rpx;
        color: #E20300;
        text {
          font-size: 24rpx;
        }
      }
      .num {
        font-size: 24rpx;
        color: #818181;
      }
    }
  }
  .settlement {
    width: 100%;
    background: rgba(255,255,255,0.9);
    position: fixed;
    bottom: 63px;
    padding: 10rpx 24rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .settlement-text {
      font-size: 28rpx;
      text {
        color: #E20300;
      }
    }
    .gwc-btn {
      width: 238rpx;
      height: 80rpx;
      background: #56CB03;
      border-radius: 200rpx;
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 28rpx;
      color: #fff;
    }
  }
}
</style>